const app = getApp();
Component({
  properties: {
    data: {
      type: JSON,
      value: 'default value',
    },
    componentState:{
      type: Boolean,
      value: true,
    },
    formDetail:{
      type: Object,
      value: 'default value',
    },
    formListStyle: {
      type: Object,
      value: 'default value',
    },
    controlLimitState: {
      type: JSON,
      value: 'default value',
    },
  },
  data: {
    setting: null, 
    formCommitItem:{},
    width:0,
    height:0,
    replyText:"",
    bannerList:{},
    conmmentList:[],
  },
  ready: function () {
    let that = this;
    console.log("====form-item-formCommitItem======", that.data.data);
    console.log("====form-item-formListStyle=====", that.data.formListStyle);
    console.log("====form-item-controlLimitState=====", that.data.controlLimitState);
    console.log("====form-item-formDetail=====", that.data.formDetail);
    console.log("====form-item-componentState=====", that.data.componentState);
    that.initData('init')
    that.setData({
      setting: app.globalData.setting,
    })
  },
  methods: {
    initData: function (data) {
      console.log("=========initData========", data)
      let that = this;
      let reqData;
      if (typeof (that.data.data) == 'object') {
        reqData = that.data.data
      } else {
        reqData = JSON.parse(that.data.data)
      }
      that.getCommentData(that.data.data.id,1)
      reqData.showFunState = false;
      reqData.showFunBan = false;
      let commitJson = reqData.commitJson
      let bannerList = that.data.bannerList
      let formListStyle = that.data.formListStyle
      for (let i in commitJson){
        if (commitJson[i].type == 11){
          bannerList[i]={
            androidTemplate:"form_more_banner",
            jsonData:{ 
               images: commitJson[i].value,
               height:'0.3',
            }
          }
        }
      }
      for(let j in bannerList){
          if(bannerList[j].jsonData.images.length!=0){
              for(let k=0;k<bannerList[j].jsonData.images.length;k++){
                  let url=bannerList[j].jsonData.images[k]
                  let obj={}
                  obj.width=150;
                  obj.imageUrl=url
                  bannerList[j].jsonData.images[k]=obj
              }
          }
      }
      console.log("=====bannerList======", bannerList)
      if (formListStyle&&formListStyle.length!=0){
        for (let i = 0; i < formListStyle.length; i++) {
          if (formListStyle[i].data.detailViewMagic && formListStyle[i].data.detailViewMagic.length != 0) {
            let detailViewMagic = formListStyle[i].data.detailViewMagic
            for (let j = 0; j < detailViewMagic.length; j++) {
              for (let key in bannerList) {
                if (detailViewMagic[j].propertieName == key) {
                  bannerList[key].jsonData.height = Math.abs(detailViewMagic[j].startPointY - detailViewMagic[j].endPointY) / Math.abs(detailViewMagic[j].startPointX - detailViewMagic[j].endPointX)
                }
              }
            }
          }
        }
      }
      that.setData({ bannerList: bannerList , formCommitItem: reqData, })
      console.log("=====databannerList======", that.data.bannerList,reqData)
      if (that.data.formListStyle) {
        that.setData({ width: Number(that.data.formListStyle.width) || 0 })
        that.setData({ height: Number(that.data.formListStyle.height) || 0 })
      }
    },
    replyTextStateFun:function(e){
      console.log("=========replyTextStateFun=====")
      let that = this;
      let type = e.currentTarget ? e.currentTarget.dataset.type : e;
      let state = (type == "show" ? true : false);
      that.data.formCommitItem.showFunBan = state
      that.setData({ formCommitItem: that.data.formCommitItem })
    },
    bindTextAreaBlur:function(e){
      console.log("=====bindTextAreaBlur====", e);
      let that=this;
      let value = e.detail.value;
      that.setData({ replyText: value})
    },
    replyTextData:function(){
      console.log("=====replyTextData====");
      let that = this;
      let params = {
        reply: that.data.replyText,
        commitId: that.data.formCommitItem.id
      }
      var customIndex = app.globalData.AddClientUrl("/super_shop_manager_reply_custom_form_commit.html", params)
      app.globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log("setStateFun", res.data)
          that.showMoreFun("hidden")
          that.replyTextStateFun('hidden')
          if (res.data.errcode == 0) {
            that.data.formCommitItem.reply = res.data.relateObj.reply
            that.setData({ formCommitItem: that.data.formCommitItem })
          } else {
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
            })
          }
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    setStateFun:function(e){
      console.log("=====setStateFun====", e);
      let that=this;
      let commitStatus = e.currentTarget.dataset.commitstatus;
      let params={
        commitStatus: commitStatus,
        commitId: that.data.formCommitItem.id
      }
      var customIndex = app.globalData.AddClientUrl("/super_shop_manager_set_commit_form_flag.html", params)
      app.globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log("setStateFun", res.data)
          if (res.data.errcode==0){
            that.showMoreFun("hidden")
            that.data.formCommitItem.recordStatus = res.data.relateObj.recordStatus
            that.setData({ formCommitItem: that.data.formCommitItem})
          }else{
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
            })
          }
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    showMoreFun:function(e){
      console.log("=====showMoreFun====", e)
      let that = this;
      let type = e.currentTarget ? e.currentTarget.dataset.type:e;
      let state = (type == "show" ? true : false);
      that.data.formCommitItem.showFunState = state
      that.setData({ formCommitItem: that.data.formCommitItem })
    },
    showMore: function (e) {
      console.log("==showMore===", e)
      let that = this;
      let type = e.currentTarget.dataset.type;
      let length = e.currentTarget.dataset.length || 2;
      let state = (type == "show" ? true : false);
      let showNum = type == "show" ? length : 2;
      that.data.formCommitItem.showMoreState = state
      that.data.formCommitItem.showNum = showNum
      that.setData({ formCommitItem: that.data.formCommitItem })
    },
    calling: function (e) {
      console.log('====e===', e)
      let phoneNumber = e.currentTarget.dataset.phonenumber
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        success: function () {
          console.log("拨打电话成功！")
        },
        fail: function () {
          console.log("拨打电话失败！")
        }
      })
    },
    checkFormDetail: function (data) {
      let that = this;
      console.log("====data===", data)
      let itemData=data.currentTarget.dataset.item ? data.currentTarget.dataset.item : {};
      let formId = itemData.id ? itemData.id : 0;
      let belongFormType = data.currentTarget.dataset.belongformtype ? data.currentTarget.dataset.belongformtype : 0;
      if (belongFormType == 0) {
        console.log("普通表单")
        wx.showActionSheet({
          itemList: ['查看用户提交的表单'],
          success: function (res) {
            console.log(res.tapIndex)
            if (!formId) {
              wx.showModal({
                title: '提示',
                content: '主人~该表单没有内容哦!',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
            } else {
              let url = "check_form_detail.html?custom_form_commit_id=" + formId
              that.tolinkUrl(url)
            }
          },
          fail: function (res) {
            console.log(res.errMsg)
          }
        })
      } else {
        console.log("信息发布表单")
        if (!formId) {
          wx.showModal({
            title: '提示',
            content: '主人~该表单没有内容哦!',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else {
          let url =""
          if(app.globalData.loginUser&&itemData.commitPlatformUserId==app.globalData.loginUser.platformUser.id){
            console.log("发布人点击",)
            wx.showActionSheet({
              itemList: ['查看详情','编辑内容'],
              success: function (res) {
                console.log(res.tapIndex)
                if (!formId) {
                  wx.showModal({
                    title: '提示',
                    content: '主人~该表单没有内容哦!',
                    success: function (res) {
                      if (res.confirm) {
                        console.log('用户点击确定')
                      } else if (res.cancel) {
                        console.log('用户点击取消')
                      }
                    }
                  })
                } else {
                  if(res.tapIndex==0){
                      url = "check_form_detail.html?custom_form_commit_id=" + formId;
                      that.tolinkUrl(url)
                  }else{
                      url = "form_detail.html?customFormId=" + itemData.belongFormId+"&userAddressCustomFormCommitId="+formId
                      that.tolinkUrl(url)
                  }
                }
              },
              fail: function (res) {
                console.log(res.errMsg)
              }
            })
          }else{
            console.log("其他用户点击查看详情")
            url = "check_form_detail.html?custom_form_commit_id=" + formId
            that.tolinkUrl(url)
          }
        }
      }
    },
    // 定位
    clickCatch: function (e) {
      console.log("===定位====", e)
      let itemData = e.currentTarget.dataset.item
      let latitude = itemData.latitude;
      let longitude = itemData.longitude;
      let name = itemData.value;
      let address = itemData.value
      wx.openLocation({
        latitude: latitude,
        longitude: longitude,
        scale: 12,
        name: name,
        address: address
      })
    },
    //获取产品分类
    getOrganizesType: function (parentCategoryId, categoryId, callback) {
      var customIndex = app.globalData.AddClientUrl("/wx_get_categories_only_by_parent.html", { categoryId: parentCategoryId })
      app.globalData.showToastLoading('loading', true)
      var that = this
      wx.request({
        url: customIndex.url,
        header: app.globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log("getOrganizesType", res.data)
          if (res.data.errcode == 0) {
            that.setData({ organizesType: res.data.relateObj })
          } else {
            that.setData({ organizesType: that.data.organizesType })
          }
          that.data.organizesType.unshift({ id: categoryId || parentCategoryId, name: "全部" })
          for (let i = 0; i < that.data.organizesType.length; i++) {
            that.data.organizesType[i].colorAtive = '#888';
          }
          that.data.organizesType[0].colorAtive = that.data.setting.platformSetting.defaultColor;
          that.data.organizesType[0].active = true;
          that.setData({ organizesType: that.data.organizesType })
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          app.globalData.loadFail()
        }
      })
    },
    toIndex() {
      app.globalData.toIndex()
    },
    tolinkUrl: function (data) {
      let linkUrl = data.currentTarget ? data.currentTarget.dataset.link : data;
      console.log("==linkUrl===", linkUrl)
      app.globalData.linkEvent(linkUrl)
    },
    onPullDownRefresh: function () {
      this.data.params.name = ""
      this.data.listPage.page = 1
      this.data.params.page = 1
      this.getData(this.data.params)
    },
    onReachBottom: function () {
      var that = this
      if (that.data.listPage.totalSize > that.data.listPage.curPage * that.data.listPage.pageSize) {
        that.data.listPage.page++
        that.data.params.page++
        that.getData(that.data.params);
      }
    },
    judgeFun:function(e){
        let that=this;
        console.log("==judgeFun==",e)
        let itemData=e.currentTarget.dataset.itemdata;
        wx.showModal({
          title: '提示',
          content: '您确定要复制文本和下载图片吗？',
          success: function (res) {
            if (res.confirm) {  
              console.log('点击确认回调')
              that.shareFormItemFun(itemData)
            } else {   
              console.log('点击取消回调')
            }
          }
        })
    },
    // 朋友圈样式方法
    shareFormItemFun:function(itemData){
        let that=this;
        let imgList=itemData.commitJson.moreImg.value;
        let value=itemData.commitJson.title.value;
        console.log("shareFormItemFun",itemData,imgList);
        if(value){
            wx.setClipboardData({
              data: value,
              success: function (res) {
                wx.getClipboardData({
                  success: function (res) {
                    wx.showToast({
                      title: '复制文本成功',
                      icon: 'success',
                      duration: 1000
                    });
                  }
                });
              }
            });
        }
        wx.authorize({
         scope: 'scope.writePhotosAlbum',
         success:function(e){
            console.log("success",e)
            setTimeout(function(){
                if(imgList&&imgList.length!=0){
                    for (let i = 0; i < imgList.length;i++){
                      that.downloadImg(imgList[i], imgList.length, i)
                    }
                }
            },1000)
         },
         fail:function(e){
            console.log("fail",e)
         },
        })
    },
    downloadImg: function(url,lengthStr,index){　　　　　　　　　　　　　　　　//触发函数
        console.log(url,lengthStr,index)
        if(url&&url.imageUrl){
            url.imageUrl=url.imageUrl.replace('http://','https://');
        }
        wx.showLoading({
            title: '图片下载中..',
        })
        wx.downloadFile({
          url: url.imageUrl,　　　　　　　//需要下载的图片url
          success: function (res) {　　　　　　　　　　　　//成功后的回调函数
            wx.saveImageToPhotosAlbum({　　　　　　　　　//保存到本地
              filePath: res.tempFilePath,
              success(res) {
                wx.hideLoading();
                wx.showToast({
                  title: '下载图片成功',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: function (err) {
                wx.hideLoading();
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                  wx.openSetting({
                    success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                        console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                    }
                  })
                }
              }
            })
          }
        });
    },
    lookBigImage: function (e) {
      console.log("111111111", e.currentTarget.dataset);
      let imgSrc = e.currentTarget.dataset.imageurl;
      let imgArray = [];
      let index = e.currentTarget.dataset.index;
      let PostImageSrc = [];
      console.log(imgSrc);

      for (let i = 0; i < imgSrc.length; i++) {
        imgArray.push(imgSrc[i].imageUrl);
        PostImageSrc.push(imgSrc[i].imageUrl.replace(/http/, "https"));
      } 
      console.log(PostImageSrc);
      if (!imgSrc) {
        return;
      }
      wx.previewImage({
        current: imgArray[index],
        // 当前显示图片的http链接
        urls: imgArray // 需要预览的图片http链接列表

      });
    },
    //获取评论数据
    getCommentData: function (customFormInstanceId, page) {
      let that = this;
      let data = {
        customFormInstanceId: customFormInstanceId,
        page: page
      }
      let customIndex = getApp().globalData.AddClientUrl("/get_news_bbs_comments.html", data)
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('====sssssss===', res)
          let conmmentList=that.conmmentList
          if (page == 1) {
            conmmentList=res.data.relateObj.result
          } else {
            console.log("====more page====");
            conmmentList=conmmentList.concat(res.data.relateObj.result)
          }
          that.setData({conmmentList:conmmentList})
          console.log("==that.conmmentList===",that.conmmentList);
        },
        fail: function (res) {//获取数据失败就会进入这个方法
          wx.hideLoading()
        }
      })
    },
    toCommentFun:function(e){
        let that=this;
        let itemData=e.currentTarget.dataset.itemdata||''
        let type=e.currentTarget.dataset.type||''
        that.triggerEvent('toComment', {itemData:itemData,type:type})
    },
  }
})